<template>
    <div class="app-container">
        <form id="fileUploadForm" method="post" action="http://up-z2.qiniu.com">
            <input name="file" type="file" />
            <input name="accept" type="hidden" />
        </form>

        <img :src="img" alt="">

        <button @click="upload">上传</button>
    </div>
</template>

<script>
const qiniu = require('qiniu')
const uuid = require('uuid/v4')
const request = require('../utils/request')
import fileUploadApi from '../api/FileUploadApi'

export default {
    name:'UploadFile',
    data:function(){
        return {
            key:uuid(),
            upToken:'',
            img:'',
        }
    },
    methods:{
        upload:function(){
            const _this = this;
            //上传的文件名使用uuid
            _this.key = uuid()
            console.log(_this.key)
            //获取formData
            var formData = new FormData(document.getElementById('fileUploadForm'))
            //从服务端获取upToken
            fileUploadApi.getUpToken()
                .then(function(data){
                    if(data == null || data.lenth == 0){
                        return
                    }
                    _this.upToken = data.toString()

                    //fileForm,upToken,key,otherOpt
                    //上传图片文件
                    fileUploadApi.upload(formData,_this.upToken,_this.key,null)
                        .then(function(data){
                            if (data.key){
                                //获取七牛云key 并生成图片外链 展示
                                _this.img = fileUploadApi.getDownloadURL(data.key)
                            }
                        })
                }).catch(function(){
                    return
                })
            
            

        }
    }

}
</script>

<style>

</style>
